package designpattern.producerconsumor;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerConsumerPattern {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		BlockingQueue sharedqueue = new LinkedBlockingQueue();
		
	     //Creating Producer and Consumer Thread
	     Thread prodThread = new Thread(new Producer(sharedqueue));
	     Thread consThread = new Thread(new Consumer(sharedqueue));

	     //Starting producer and Consumer thread
	     prodThread.start();
	     consThread.start();
	     
	     


	}

	static class Producer implements Runnable {
		private final BlockingQueue sharedqueue;
		
		

		public Producer(BlockingQueue sharedqueue) {
			this.sharedqueue = sharedqueue;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			for (int i = 0; i < 10; i++) {
				try {
					System.out.println("Produced: " + i);
					sharedqueue.put(i);
					Thread.sleep(10);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}

	}

	static class Consumer implements Runnable {

		private final BlockingQueue sharedqueue;

		public Consumer(BlockingQueue sharedqueue) {
			this.sharedqueue = sharedqueue;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (true) {
				try {
					System.out.println("Consumed: " + sharedqueue.take());
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

	}

}
